#include "KcpReceiver.h"
#include <cstring>

KCPReceiver::KCPReceiver()
:m_IsRunning(false)
{

}

KCPReceiver::~KCPReceiver()
{
    if (m_IsRunning)
    {
        m_IsRunning = false;
        pthread_join(m_Thread_id, NULL);
    }
}

int KCPReceiver::InitReceiver(const char* local_ip, int local_port)
{
    int ret = 0;
    KcpPeerConfig config;
    strcpy(config.local_ip, local_ip);
    config.local_port = local_port;
    strcpy(config.remote_ip, "0.0.0.0");
    config.remote_port = 9999;
    ret = PeerCreate(config);
    if (ret != 0) {
        printf("PeerCreate failed\n");
        return -1;
    }

    if (pthread_create(&m_Thread_id, NULL, ReceiveDataThread, (void *)this) != 0)
    {
        printf("Could not start send data thread\n");
		return -1;
	}

    return 0;
}

void* KCPReceiver::ReceiveDataThread(void *arg)
{
    KCPReceiver* receiver = (KCPReceiver*)arg;
    receiver->m_IsRunning = true;
    while (receiver->m_IsRunning)
    {
        receiver->KcpSync();
        usleep(1 * 1000);
    }

    return NULL;
}